/*
 * @Author: wangjq4214
 * @Date: 2022-05-04 09:27:14
 * @LastEditTime: 2022-05-07 18:55:14
 * @LastEditors: wangjq4214
 */
import { get as getReq } from '@/apis';
import { NodelistRes, NODE_LIST_URL } from '@/apis/docker';
import { SRORAGE_LIST_URL, StorageList } from '@/apis/storage';

const resultAtom = atom<{
  loading: boolean;
  error: null | unknown;
  data: null | StorageList;
}>({
  loading: true,
  error: null,
  data: null,
});

export const paginationAtom = atom({ current: 1, pageSize: 20 });

export const listAtom = atom(
  (get) => get(resultAtom),
  (get, set) => {
    const fetcher = async () => {
      set(resultAtom, (prev) => ({ ...prev, loading: true }));
      try {
        const pagination = get(paginationAtom);

        const data = await getReq<StorageList>(SRORAGE_LIST_URL, {
          page: pagination.current,
          size: pagination.pageSize,
        });

        set(resultAtom, { loading: false, error: null, data });
      } catch (error) {
        set(resultAtom, { loading: false, error, data: null });
      }
    };

    fetcher();
  }
);

export const visibleAtom = atom(false);

const rawNodeListAtom = atom<{
  loading: boolean;
  error: null | unknown;
  data: null | NodelistRes;
}>({
  loading: true,
  error: null,
  data: null,
});

// export const nodeListAtom = atom(
//   (get) => get(rawNodeListAtom),
//   (get, set) => {
//     const fetcher = async () => {
//       set(rawNodeListAtom, (prev) => ({ ...prev, loading: true }));
//       try {
//         const pagination = get(paginationAtom);

//         const data = await getReq<NodelistRes>(NODE_LIST_URL, {
//           page: pagination.current,
//           size: pagination.pageSize,
//         });

//         set(rawNodeListAtom, { loading: false, error: null, data });
//       } catch (error) {
//         set(rawNodeListAtom, { loading: false, error, data: null });
//       }
//     };

//     fetcher();
//   }
// );

export const selectIDAtom = atom('');
